const koaRouter = require('koa-router');
const request = require('request');
const sha1 = require('sha1');

// 佛山市匠来家居有限公司
const APP_ID = 'wxb7fb3106bb2cafd6';
const APP_SECRET = '67f5514af94671d028cc35b51ac181bb';
let nonceStr = '';
let timestamp = '';


const router = new koaRouter({
    prefix: '/api/pay'
});

/**
 * 前端请求此接口获取config
 */
router.get('/recharge', async ctx => {
    let url = ctx.headers['host'] + ctx.url;

    let resToken = await getToken();

    let resTicket = await getTicket(resToken);

    console.log('resTicket', resTicket);

    return ctx.body = {
        code: 0,
        msg: 'success',
        responseData: {
            appId: APP_ID,
            signature: signature(resTicket, url),
            timestamp,
            nonceStr
        }
    };
});

/* 
* 获取token 
*/
function getToken () {  
    return new Promise((resolve, reject) => {
        request.post({
            url: 'https://api.weixin.qq.com/cgi-bin/token',
            form: {
                appid: APP_ID,
                secret: APP_SECRET,
                grant_type: 'client_credential'
            }
        }, (error, response, body) => {
            if (error) {
                console.error(error);
                reject(error);
            }
            body = JSON.parse(body);
            resolve(body.access_token); 
        });
    });
}

/* 通过token，获取jsapi_ticket */
function getTicket(accessToken) {
    return new Promise((resolve, reject) => {
        request.post({
            url: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
            form: {
                type: 'jsapi',
                access_token: accessToken
            }
        }, (error, response, body) => {
            if (error) {
                console.error(error);
                reject(error);
            }
            body = JSON.parse(body);
            resolve(body.ticket);
        });
    });
}

/**
 * 签名算法
 * @param ticket 用于签名的 jsapi_ticket
 * @param url 用于签名的 url ，注意必须动态获取
 * @return sha1算法加密的字符串
 */
function signature (ticket, url) {
    // 生成随机字符串
    nonceStr = createNonceStr(); 

    // 获取当前时间戳
    timestamp = createTimestamp();
    
    let ret = {
        jsapi_ticket: ticket,
        nonceStr,
        timestamp,
        url: url
    }
    
    // 排序拼接为字符串
    let string = raw(ret);

    // 返回sha1加密的字符串
    return sha1(string); 
}

/* 
* 生成随机字符串 
*/
function createNonceStr() {
    return Math.random().toString(36).substr(2, 15);
}

/* 
* 获取当前时间戳 
*/
function createTimestamp() {
    return parseInt(new Date().getTime() / 1000) + '';
}

/* 
* 排序拼接 
*/
function raw (args) {
    // 获取args对象的键值数组
    var keys = Object.keys(args);

    // 对所有待签名参数按照字段名的ASCII 码从小到大排序（字典序）
    keys = keys.sort(); 

    var newArgs = {};

    // 所有参数名均为小写字符，按照排序重新生成一个对象
    keys.forEach(key => {
        newArgs[key.toLowerCase()] = args[key];
    });


    var string = '';

    // 循环新对象，拼接为字符串
    for (var k in newArgs) { 
        string += '&' + k + '=' + newArgs[k];
    }

    // 截取第一个字符以后的字符串（去掉第一个‘&’）
    string = string.substr(1);
    return string;
}

module.exports = router;
